package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;//套接字

    public Client(){
        /*
          Socket实例化时需要传入两个参数
          1:服务端的地址信息
          2:服务端打开的服务端口
          客户端通过服务端的地址找到网络上的服务器计算机，通过端口可以连接上该机器上运行的服务端应用程序
         */
        try {
            System.out.println("正在连接服务端...");
            socket = new Socket("localhost",8088);
            System.out.println("与服务端建立连接！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        //将读取来自服务端消息的线程启动起来
        ServerHandler serverHandler = new ServerHandler();
        Thread t = new Thread(serverHandler);
        t.setDaemon(true);//设置为守护线程
        t.start();


        //客户端向服务器发送数据，则需要使用socket获取输出流
        try {
            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);


            Scanner scan = new Scanner(System.in);
            while (true){
                String data = scan.nextLine();
                if("exit".equals(data)){
                    break;
                }
                pw.println(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args){
        Client client = new Client();
        client.start();
    }

    private class ServerHandler implements Runnable{
        public void run() {
            try {
                //通过socket获取输入流，用于读取服务端发送过来的消息
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in,StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String line;
                while((line = br.readLine())!=null){
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
